package com.ruoyi.pcwl.controller;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.pcwl.domain.MinioFile;
import com.ruoyi.pcwl.domain.enums.MediaTypeEnum;
import com.ruoyi.pcwl.minio.MinioUtil;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Item;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "文件上传接口")
@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {


    @ApiOperation("获取文件列表")
    @GetMapping("/list")
    public AjaxResult list() throws Exception {
        //获取bucket列表
        ArrayList<MinioFile> mediaFileList = MinioUtil.getMediaFileList(null);
//        Iterable<Result<Item>> results = minioClient.listObjects(
//                ListObjectsArgs.builder().bucket(bucketName).build());
//
//        for (Result<Item> myObject : results) {
//            Item item = myObject.get();
//            System.out.println(item.lastModified() + ", " + item.size() + ", " + item.objectName());
//        }
        return AjaxResult.success(mediaFileList);
    }

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public AjaxResult upload(Integer categoryId,MultipartFile[] file) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, XmlParserException, InvalidResponseException, InternalException {
        if (file == null || file.length == 0) {
            return AjaxResult.error("上传文件不能为空");
        }
        List<String> fileNameList = new ArrayList<>(file.length);
        Map<String, Object> map = null;
        for (MultipartFile multipartFile : file) {
            switch (categoryId){
                case 1:
                    map = MinioUtil.uploadFile(multipartFile, MediaTypeEnum.CAROUSEL);
                    fileNameList.add((String) map.get("path"));
                    break;
                case 2:
                    map = MinioUtil.uploadFile(multipartFile, MediaTypeEnum.VEDIO);
                    fileNameList.add((String) map.get("path"));
                    break;
                case 3:
                    map = MinioUtil.uploadFile(multipartFile,MediaTypeEnum.PCWLSHOPENV);
                    fileNameList.add((String) map.get("path"));
                    break;
                case 4:
                    map = MinioUtil.uploadFile(multipartFile,MediaTypeEnum.PCWLSHOPDETAILS);
                    fileNameList.add((String) map.get("path"));
                    break;
                case 5:
                    map =  MinioUtil.uploadFile(multipartFile,MediaTypeEnum.SCENICSPOT);
                    fileNameList.add((String) map.get("path"));
                    break;
                case 6:
                    map = MinioUtil.uploadFile(multipartFile,MediaTypeEnum.HOTEL);
                    fileNameList.add((String) map.get("path"));
                    break;
                case 7:
                    map = MinioUtil.uploadFile(multipartFile,MediaTypeEnum.PCWLSHOP);
                    fileNameList.add((String) map.get("path"));
                    break;
                case 8:
                    map = MinioUtil.uploadFile(multipartFile,MediaTypeEnum.TRAVEL);
                    fileNameList.add((String) map.get("path"));
                    break;
                default:
                    return AjaxResult.error("上传失败");
            }
        }
        return AjaxResult.success("上传成功", fileNameList);
    }

//    @GetMapping("/download/{fileName}")
//    public void download(HttpServletResponse response, @PathVariable("fileName")
//            String fileName) {
//        InputStream in = null;
//        try {
//            // 获取对象信息
//            ObjectStat objectStat = minioClient.statObject(
//
//                    StatObjectArgs.builder().bucket(bucketName).object(fileName).build());
//            response.setContentType(objectStat.contentType());
//            response.setHeader("Content-Disposition", "attachment;filename=" +
//                    URLEncoder.encode(fileName, "UTF-8"));
//            //文件下载
//            in = minioClient.getObject(
//
//                    GetObjectArgs.builder()
//                            .bucket(bucketName)
//                            .object(fileName)
//                            .build());
//            IOUtils.copy(in, response.getOutputStream());
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        } finally {
//            if (in != null) {
//                try {
//                    in.close();
//                } catch (IOException e) {
//                    log.error(e.getMessage());
//                }
//            }
//        }
//    }
//
//    @DeleteMapping("/delete/{fileName}")
//    public AjaxResult delete(@PathVariable("fileName") String fileName) {
//        try {
//            minioClient.removeObject(
//
//                    RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
//        } catch (Exception e) {
//            log.error(e.getMessage());
//            return AjaxResult.error("删除失败");
//        }
//        return AjaxResult.success("删除成功", null);
//    }
//
//    private static String formatFileSize(long fileS) {
//        DecimalFormat df = new DecimalFormat("#.00");
//        String fileSizeString = "";
//        String wrongSize = "0B";
//        if (fileS == 0) {
//            return wrongSize;
//        }
//        if (fileS < 1024) {
//            fileSizeString = df.format((double) fileS) + " B";
//        } else if (fileS < 1048576) {
//            fileSizeString = df.format((double) fileS / 1024) + " KB";
//        } else if (fileS < 1073741824) {
//            fileSizeString = df.format((double) fileS / 1048576) + " MB";
//        } else {
//            fileSizeString = df.format((double) fileS / 1073741824) + " GB";
//        }
//        return fileSizeString;
//    }
}
